package com.starbaba.userpoint.service.impl;

import java.util.List;
import java.util.Map;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.db.CommUser;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.userpoint.model.UserPointModel;
import com.starbaba.userpoint.service.UserPointService;

@SuppressWarnings("rawtypes")
public class UserPointServiceImpl implements UserPointService{
	
	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
    
	@Override
	public List<UserPointModel> getDataList(int iDisplayStart, int iDisplayLength, 
			PageResponse pageResponse, Map<String, Object> paramsMap) {
				
		String platform = (String) paramsMap.get("platform");
		String prd_type = (String) paramsMap.get("prd_type");
		String channel = (String) paramsMap.get("channel");
        String mobnum = (String) paramsMap.get("mobnum");
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String type = (String)paramsMap.get("type");
		
		String sql = "select a.userid, a.mobnum, a.value, a.platform, a.prd_type, b.channel_name, a.operator, "
				+ " a.ctime, a.type, a.opr_type, a.memo from user_point_details a LEFT JOIN comm_product_channel b "
				+ " on (a.channel = b.channel_code) where 1=1 ";
				
		String selectSql = "";
		if (!StringUtils.isEmpty(platform)) {
            selectSql += " and a.platform = '" + platform +"'";
        }
		if (!StringUtils.isEmpty(prd_type)) {
			selectSql += " and a.prd_type = '" + prd_type + "'";
		}
		if (!StringUtils.isEmpty(mobnum)) {
			selectSql += " and a.mobnum = '" + mobnum + "'";
		}
		if (!StringUtils.isEmpty(channel)) {
            selectSql += " and a.channel = " + channel;
        }
		if (!StringUtils.isEmpty(startTime)) {
            selectSql += " and a.ctime >= '" + startTime +" 00:00:00'";
        }
		if (!StringUtils.isEmpty(endTime)) {
            selectSql += " and a.ctime <= '" + endTime +" 23:59:59'";
        }
		if (!StringUtils.isEmpty(type)) {
            selectSql += " and a.type = " + type;
        }
		
		sql += selectSql;
		sql += " order by a.ctime desc ";
		
		if (sql.length() > 0 && iDisplayStart >= 0 && iDisplayLength > 0) {
			sql += " limit " + iDisplayStart + " , " + iDisplayLength;
		}

		String countSql = "select count(1) from user_point_details a where 1=1 " + selectSql;
		List<UserPointModel> list = null;
		try {
			int count = dao.getInt(countSql);
			list = dao.list(sql, UserPointModel.class, new Object[] {});
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String exportLoanOrderCVS(List<UserPointModel> list) {
		
		StringBuffer sf = new StringBuffer();
		sf.append("平台,产品,渠道,用户ID,手机号,更新时间,积分变化,所属活动,操作人,备注\r\n");

		for (UserPointModel vo : list) {
			sf.append("'" + vo.getPlatform()).append(",");
			sf.append(vo.getPrd_type()).append(",");
			sf.append("'" + vo.getChannel_name()).append(",");
			sf.append("'" + vo.getUserid()).append(",");
			sf.append("'" + vo.getMobnum()).append(",");
			sf.append("'" + vo.getCtime()).append(",");
			if (vo.getOpr_type() == 1) {
				sf.append("+").append(vo.getValue()).append(",");
			} else {
				sf.append("-").append(vo.getValue()).append(",");
			}
			Integer type = vo.getType();
			switch (type) {
			case 1:
				sf.append("邀请好友").append(",");
				break;
			case 666:
				sf.append("用户提现").append(",");
				break;
			default:
				sf.append("--").append(",");
			    break;
			}
			sf.append(vo.getOperator()).append(",");
			sf.append(vo.getMemo()).append(",");
			sf.append("\r\n");
		}
		return sf.toString();
	}

	@Override
	public List<UserPointModel> getUserPointList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, Map<String, Object> paramsMap) {
		
        String mobnum = (String) paramsMap.get("mobnum");
        String prd_type = (String) paramsMap.get("prd_type");
		
		String sql = "select a.userid, a.mobnum, a.value avalue, b.value bvalue, a.prd_type "
				+ " from ((select userid, mobnum, sum(value) value, prd_type from user_point_details where opr_type = 1 GROUP BY userid, prd_type) a "
				+ " LEFT JOIN (select userid, mobnum, sum(value) value, prd_type from user_point_details where opr_type = 2 GROUP BY userid, prd_type) b ON (a.userid = b.userid)) where 1=1 ";
				
		String selectSql = "";
		if (!StringUtils.isEmpty(mobnum)) {
			selectSql += " and a.mobnum = '" + mobnum +"'";
		}
		if (!StringUtils.isEmpty(prd_type)) {
			selectSql += " and a.prd_type = '" + prd_type +"'";
		}
		sql += selectSql;
	
		if (sql.length() > 0 && iDisplayStart >= 0 && iDisplayLength > 0) {
			sql += " limit " + iDisplayStart + " , " + iDisplayLength;
		}

		String countSql = "select count(DISTINCT mobnum) from user_point_details a where 1=1 " + selectSql;
		List<UserPointModel> list = null;
		try {
			int count = dao.getInt(countSql);
			list = dao.list(sql, UserPointModel.class, new Object[] {});
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String userPointManage(Map<String, Object> paramsMap) {
        
		String type = (String) paramsMap.get("type");
		String value = (String) paramsMap.get("value");
		String memo = (String) paramsMap.get("memo");
		String operator = (String) paramsMap.get("operator");
		String prd_type = (String) paramsMap.get("prd_type");
		Long userId = Long.parseLong((String) paramsMap.get("userid"));

		UserPointModel model = new UserPointModel();

		try {
			CommUser user = new CommUser();
			user.setId(userId);
			user = dao.get(user, new String[] { "id" });
			if (user != null) {
				model.setMobnum(user.getMobnum());
			}
		} catch (Exception e) {
			LogService.error(e);
		}
		model.setUserid(userId);
		Integer aValue = Integer.parseInt(value);
		if ("1".equals(type)) {
			model.setType(9);
			model.setOpr_type(1); // 增加积分
			if (StringUtils.isEmpty(memo)) {
				memo = "运营增加积分";
			}
		} else if ("2".equals(type)) {
			if(queryPointByuserId(userId, prd_type) < aValue){
				return "积分不足";
			}
			model.setType(666);
			model.setOpr_type(2); // 扣减积分
			if (StringUtils.isEmpty(memo)) {
				memo = "运营扣减积分";
			}
		}
		model.setValue(aValue);
		model.setPrd_type(prd_type);
		model.setOperator(operator);
		model.setMemo(memo);
		try {
			dao.add(model);
			return "SUCCESS";
		} catch (AppException e) {
			LogService.error(e);
		}
		return "FAILED";
	}

	@Override
	public Integer queryPointByuserId(Long userId, String prdType) {

		try {
			String sql = "select a.userid, a.mobnum, a.value avalue, b.value bvalue "
					+ " from ((select userid, mobnum, prd_type, sum(value) value from user_point_details where opr_type = 1 GROUP BY userid) a "
					+ " LEFT JOIN (select userid, mobnum, sum(value) value from user_point_details where opr_type = 2 GROUP BY userid) b "
					+ " ON (a.userid = b.userid)) where a.userid= ? and a.prd_type = ?";

			UserPointModel model = dao.get(sql, UserPointModel.class, userId, prdType);

			if (model != null) {
				int aValue = 0;
				int bValue = 0;
				if (model.getAvalue() != null) {
					aValue = model.getAvalue();
				}
				if (model.getBvalue() != null) {
					bValue = model.getBvalue();
				}
				return aValue - bValue;
			}
		} catch (AppException e) {
			LogService.error(e);
		}
		return null;
	}
}
